package res.levels.xmlLE;
/**
Java Swing, 2nd Edition
By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole
ISBN: 0-596-00408-7
Publisher: O'Reilly 
*/
// VSX.java
//A simple XML parser that builds a tree from SAX events. 
//

import java.io.File;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeModel;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;


import java.util.HashMap;

public class VSX {

  public TreeModel parse(String filename) {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    XMLTreeHandler handler = new XMLTreeHandler();
    try {
      // Parse the input.
      SAXParser saxParser = factory.newSAXParser();
      saxParser.parse(new File(filename), handler);
    } catch (Exception e) {
      System.err.println("File Read Error: " + e);
      e.printStackTrace();
      return new DefaultTreeModel(new DefaultMutableTreeNode("error"));
    }
    return new DefaultTreeModel(handler.getRoot());
  }

  public static class XMLTreeHandler extends DefaultHandler {
    private DefaultMutableTreeNode root, currentNode;

    public DefaultMutableTreeNode getRoot() {
      return root;
    }

    // SAX Parser Handler methods...
    public void startElement(String namespaceURI, String lName,
        String qName, Attributes attrs) throws SAXException {
      String eName = lName; // Element name
		int length = attrs.getLength();
		Tag t = new Tag(lName,new HashMap<String,String>());
		for (int i=0; i<length; i++) {
            // Get names and values for each attribute
            String name = attrs.getQName(i);
            String value = attrs.getValue(i);
			t.tags.put(name,value);
        }
      
      
      if ("".equals(eName))
        eName = qName;
		t.name =eName;
      DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(t);
      if (currentNode == null) {
        root = newNode;
      } else {
        // Must not be the root node...
        currentNode.add(newNode);
      }
      currentNode = newNode;
    }

    public void endElement(String namespaceURI, String sName, String qName)
        throws SAXException {
      currentNode = (DefaultMutableTreeNode) currentNode.getParent();
    }

    public void characters(char buf[], int offset, int len)
        throws SAXException {
      String s = new String(buf, offset, len).trim();
      ((Tag) currentNode.getUserObject()).data=s;
    }
  }

  
}
